//
//  ViewController.m
//  PSCollectionViewDemo
//
//  Created by Eric on 12-6-14.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "lxGoodsListViewController.h"
#import "PSCollectionViewCell.h"
#import "lxGoodsCell.h"
#import "lxGoodsEntity.h"
#import "lxGoodsDetailViewController.h"

#ifndef LUN_SELECT_GOODS_LIST_COUNT
    #define LUN_SELECT_GOODS_LIST_COUNT 20
#endif

@interface lxGoodsListViewController ()

@end

@implementation lxGoodsListViewController
@synthesize collectionView = _collectionView;
@synthesize cat_id = _cat_id;

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.tintColor = [UIColor orangeColor];
    self.title = _cat_name;
    UIBarButtonItem *reflash_bt = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"reflash_bt", nil) style:UIBarButtonItemStyleBordered target:self action:@selector(leftReflashBtClick:)];
    self.reFlash_bt = reflash_bt;
    [reflash_bt release];
}

- (void)leftReflashBtClick:(id)sender {
    [self reFlash];
}

- (void)reFlash {
    [self reFlashList];
}

- (void)dealloc{
    [_collectionView release];
    [_arrayList release];
    _arrayList_tmp = nil;
    _isRefreshTable = YES;
    _cat_id = 0;
    [super dealloc];
}

- (void)subViewDidLoad
{
    _isRefreshTable = YES;    
    self.is_supportShakeToEdit = YES;
    self.is_supportHandleSwipeFrom = YES;
    
    _cat_name = NSLocalizedString(@"goods_list", nil);
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    _arrayList = [[NSMutableArray alloc]initWithCapacity:5];

    self.collectionView = [[PullPsCollectionView alloc] initWithFrame:self.view.bounds];
    self.collectionView.collectionViewDelegate = self;
    self.collectionView.collectionViewDataSource = self;
    self.collectionView.pullDelegate=self;
    self.collectionView.backgroundColor = [UIColor clearColor];
    self.collectionView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    
    self.collectionView.numColsPortrait = 1;
    self.collectionView.numColsLandscape = 1;
    if (ISIPADDEVICE) {
        self.collectionView.numColsPortrait = 2;
        self.collectionView.numColsLandscape = 2;
    }
    
    self.collectionView.pullArrowImage = [UIImage imageNamed:@"blackArrow"];
    self.collectionView.pullBackgroundColor = [UIColor grayColor];
    self.collectionView.pullTextColor = [UIColor blackColor];
/*
    UILabel *loadingLabel = [[UILabel alloc] initWithFrame:self.collectionView.bounds];
    loadingLabel.text = NSLocalizedString(@"loading", nil);
    loadingLabel.textAlignment = NSTextAlignmentCenter;
    self.collectionView.loadingView = loadingLabel;
 */ 
    [self.view addSubview:self.collectionView];
}

- (void) refreshTable
{
    if(nil ==_arrayList_tmp) {
        return;
    }
//    self.collectionView.scrollsToTop = YES;
    [_arrayList removeAllObjects];
    [self loadDataSource];
    self.collectionView.pullLastRefreshDate = [NSDate date];
    self.collectionView.pullTableIsRefreshing = NO;
    [self.collectionView reloadData];
}

- (void) loadMoreDataToTable
{
    if(nil ==_arrayList_tmp) {
        return;
    }

    [_arrayList addObjectsFromArray:_arrayList_tmp];
    [self.collectionView reloadData];
    self.collectionView.pullTableIsLoadingMore = NO;
}
#pragma mark - PullTableViewDelegate

- (void)pullPsCollectionViewDidTriggerRefresh:(PullPsCollectionView *)pullTableView
{
    _isRefreshTable = YES;
    [self sendRequest];
}

- (void)pullPsCollectionViewDidTriggerLoadMore:(PullPsCollectionView *)pullTableView
{
    _isRefreshTable = NO;
    [self sendRequest];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

- (PSCollectionViewCell *)collectionView:(PSCollectionView *)collectionView viewAtIndex:(NSInteger)index {
    int count = [_arrayList count];
    NSLog(@"[tableView]arrayList count:%d", count);
    
    if (count < 1) {
        return nil;
    }
    
    // You should probably subclass PSCollectionViewCell
    lxGoodsCell *cell = (lxGoodsCell *)[self.collectionView dequeueReusableView];
    if(cell == nil) {
        CGRect ret = CGRectMake(0, 0, collectionView.bounds.size.width, collectionView.bounds.size.height / 4);
        cell = [[[lxGoodsCell alloc] initWithFrame:ret] autorelease];
    }
    
    lxGoodsEntity *goodsEntity = nil;
    if (index <= count - 1) {
        NSDictionary *dictionary = [_arrayList objectAtIndex:index];
        
        goodsEntity = [[lxGoodsEntity alloc] init];
        
        BOOL result = [goodsEntity setEntity:dictionary];
        if (YES == result) {
            [cell refreshData:goodsEntity];
        }
    }
    return cell;
}

- (CGFloat)heightForViewAtIndex:(NSInteger)index {
    float cell_height = self.collectionView.bounds.size.height / 4;
    return cell_height;
}

- (void)collectionView:(PSCollectionView *)collectionView didSelectView:(PSCollectionViewCell *)view atIndex:(NSInteger)index {
    // Do something with the tap
    NSLog(@"index=%d", index);
    if (nil == _arrayList) {
        NSLog(@"arrayList is nil");
        return;
    }
    
    int arrayList_count = [_arrayList count];
    NSLog(@"arrayList_count=%d", arrayList_count);
    if (arrayList_count - 1 < index) {
        return;
    }
    
    //Add Cell event.
    
    NSDictionary *dictionary = [_arrayList objectAtIndex:index];
    lxGoodsEntity *goodsEntity = [[lxGoodsEntity alloc] init];
    BOOL result = [goodsEntity setEntity:dictionary];
    if (YES == result) {
        lxGoodsDetailViewController *lxGDVC = [[lxGoodsDetailViewController alloc] init];
        lxGDVC.lxGE.goods_id = goodsEntity.goods_id;
        [self.navigationController pushViewController:lxGDVC animated:YES];
        [lxGDVC reFlash];
        [lxGDVC release];
    }
}

- (NSInteger)numberOfViewsInCollectionView:(PSCollectionView *)collectionView {
    return [_arrayList count];
}

- (void)loadDataSource {
    // Request    
    for (NSDictionary *dictionary in _arrayList_tmp) {
        if (nil != dictionary) {
            [_arrayList addObject:dictionary];
        }
    }
    [_collectionView reloadData];
}

- (void)reFlashList {
    if(!_collectionView.pullTableIsRefreshing) {
        lxAPPContainer *appContainer = [lxAPPContainer sharedLxAPPContainer];
        if (YES == [appContainer isExistNet]) {
            _collectionView.pullTableIsRefreshing = YES;
            _isRefreshTable = YES;
            [self sendRequest];
            self.is_loading = YES;
        }
    }
}

#pragma mark -
#pragma mark ASIHTTPRequestDelegate Methods
- (ASIHTTPRequest *)sendRequest:(BOOL)isStartAsynchronous {
    lxAPPContainer *appContainer = [lxAPPContainer sharedLxAPPContainer];
    if (NO == [appContainer isExistNet]) {
        return nil;
    }
    
    int start_row = 0;
    if (NO == _isRefreshTable) {
        start_row = [_arrayList count];
    }
    
    int row_count = LUN_SELECT_GOODS_LIST_COUNT;
    NSString *str_url = [NSString stringWithFormat:@"%@%@?cat_id=%d&start_row=%d&row_count=%d", service_url, getGoodsListServlet, _cat_id, start_row, row_count];
    NSURL *url = [NSURL URLWithString:str_url];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    [request setDelegate:self];
    
    if (YES == isStartAsynchronous) {
        [request startAsynchronous];
    } else {
        [request startSynchronous];
    }
    return request;
}

- (ASIHTTPRequest *)sendRequest {
    lxAPPContainer *appContainer = [lxAPPContainer sharedLxAPPContainer];
    if (NO == [appContainer isExistNet]) {
        return nil;
    }
    
    int start_row = 0;
    if (NO == _isRefreshTable) {
        start_row = [_arrayList count];
    }

    int row_count = LUN_SELECT_GOODS_LIST_COUNT;
    NSString *str_url = [NSString stringWithFormat:@"%@%@?cat_id=%d&start_row=%d&row_count=%d", service_url, getGoodsListServlet, _cat_id, start_row, row_count];
    NSURL *url = [NSURL URLWithString:str_url];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    [request setDelegate:self];
    [request startAsynchronous];
    return request;
}

- (void)getResponse:(ASIHTTPRequest *)request {
    _arrayList_tmp = nil;
    NSString *responseString = [request responseString];
    
    if (![responseString isKindOfClass:[NSString class]]) {
        NSLog(@"reponsedate is nil");
        return;
    }
    
    if ([lxStringUtility isNil:responseString]) {
        NSLog(@"reponsedate is nil");
        return;
    }
    
    NSData *reponsedata = [responseString dataUsingEncoding:NSUTF8StringEncoding];
    
    if (nil == reponsedata) {
        NSLog(@"reponsedate is nil");
        return;
    }
    
    if (![reponsedata isKindOfClass:[NSData class]]) {
        NSLog(@"reponsedate is nil");
        return;
    }
    
    __autoreleasing NSError *error = nil;
    
    NSDictionary *dictionaryAll = [NSJSONSerialization JSONObjectWithData:reponsedata options:kNilOptions error:&error];

    if (nil == dictionaryAll) {
        NSLog(@"init Response failed because:%@", [error localizedDescription]);
        return;
    }
    
    if (![dictionaryAll isKindOfClass:[NSDictionary class]]) {
        NSLog(@"init Response failed because:%@", [error localizedDescription]);
        return;
    }
    
    NSString *cat_name = [dictionaryAll objectForKey:@"name"];
    if (![lxStringUtility isNil:cat_name]) {
        _cat_name = cat_name;
        [_cat_name retain];
        self.title = _cat_name;
    }
    
    _arrayList_tmp = [dictionaryAll objectForKey:@"goods"];
    if (nil == _arrayList_tmp) {
        NSLog(@"Response failed because:%@", [error localizedDescription]);
        return;
    }
    
    if (![_arrayList_tmp isKindOfClass:[NSArray class]]) {
        NSLog(@"Response failed because:%@", [error localizedDescription]);
        _arrayList_tmp = nil;
        return;
    }
    
    int count = [_arrayList_tmp count];
    if (count < 1) {
        NSLog(@"Response failed because:reponsedata is nothing");
        _arrayList_tmp = nil;
        return;
    } 
    return;
}

- (void)requestFinished:(ASIHTTPRequest *)request {
    [self getResponse:request];
    if (YES == _isRefreshTable) {
        [self refreshTable];
    } else {
        [self loadMoreDataToTable];
    }
    self.collectionView.pullTableIsRefreshing = NO;
    _isRefreshTable = YES;
    self.is_loading = NO;
}

- (void)requestFailed:(ASIHTTPRequest *)request {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"error", nil)
                                                    message:NSLocalizedString(@"network_conn_failed", nil)
                                                   delegate:self
                                          cancelButtonTitle:NSLocalizedString(@"ok", nil)
                                          otherButtonTitles:nil];
    [alert show];
    [alert release];
    self.collectionView.pullTableIsRefreshing = NO;
    _isRefreshTable = YES;
    self.is_loading = NO;
}

@end
